--[[-------------------------------------------------------------------------
    ArathiBasinFu by Viserion of Thrall <eiseimaru@gmail.com>
    
	Forks or modifications of this addon are strictly prohibited. If you would like
	to contribute to the codebase please contact the author
---------------------------------------------------------------------------]]

--[[---------------------------------------------------------------------------------
    Library instances that we will be using in this plugin
----------------------------------------------------------------------------------]]
local glory_ = AceLibrary("glory_-2.0")
local tablet_ = AceLibrary("tablet_-2.0")
local waterfall_ = AceLibrary("Waterfall-1.0")

--[[---------------------------------------------------------------------------------
  Create the AddOn object 
----------------------------------------------------------------------------------]]
ArathiBasinFu = AceLibrary("AceAddon-2.0"):new(
	"AceDebug-2.0",
	"AceEvent-2.0",
	"FuBarPlugin-2.0",
	"AceDB-2.0",
	"AceConsole-2.0"
)


local L = setmetatable({}, {__index = function(self, key) self[key] = key; return key end }) --placeholder for localization

ArathiBasinFu.hasIcon = true -- Kind of annoying this has to be placed here
	
function ArathiBasinFu:PrintAlertMessage(message, custom)
    if self:IsDebugging() then
        self:Debug(message)
    else
        SendChatMessage(message, "BATTLEGROUND")
    end
end

function ArathiBasinFu:BuildAlertMessage(numberOfEnemies)
	if glory_:IsInArathiBasin() or self:IsDebugging() then
		local location = GetSubZoneText()
		local profile = self.db.profile -- TODO: use this once formating is reworked
	
		if numberOfEnemies > 1 then
			if numberOfEnemies == profile.enemyThreshold - 1 then
				self:PrintAlertMessage(L["%d+ Incoming %s"]:format(numberOfEnemies, location), false)
				return
			elseif numberOfEnemies == profile.enemyThreshold then
				self:PrintAlertMessage(L["Zerg Incoming %s"]:format(location), false)
				return
			else
				self:PrintAlertMessage(L["%d Incoming %s"]:format(numberOfEnemies, location), false)
				return
			end
		else
            self:PrintAlertMessage(L["Incoming %s"]:format(location), false)
		end
	end
end

function ArathiBasinFu:TestStuff()
	--self:Print(Version)
end

function ArathiBasinFu:LoadOptions()
	local options = {
		type = "group",
		args = {
			placeholder = {
				type = "execute",
				name = L["Debug Test"],
				desc = L["Debug test routine"],
				func = function()  self:TestStuff() end,
			},
		
			enemyThreshold = {
				type = "range",
				name = L["Enemy Threshold"],
    			desc = L["Change enemy threshold"],
    			get = function()
        			return self.db.profile.enemyThreshold
    			end,
    			set = function(v)
        			self.db.profile.enemyThreshold = v
    			end,
    			min = 1,
    			max = 10, 
    			step = 1, 
    			isPercent = false,
    		},
			
			addCustomMessage = {
				type = "text",
				name = L["Add Custom Message"],
				desc = L["Adds a new custom message to be sent to /bg."],
				usage = L["<Title> # <Message>"],
				get = false,
				set = function(v) self:AddMessage(v) end,
				validate = function(v) return string.find(v, "(.*)%s+#%s+(.*)") end,
			},
			
			removeCustomMessage = {
				type = "text",
				name = L["Remove Custom Message"],
				desc = L["Remove a custom message"],
				usage = L["<Title>"],
				get = false,
				set = function(v) self:RemoveMessage(v) end,
			},
		}
	}
	
    
    local slashMenu =
    {
        type = 'execute',
        func = function()
            if not (UnitAffectingCombat("player")) then
                waterfall_:Open("ArathiBasinFu")
            else
                DEFAULT_CHAT_FRAME:AddMessage("|cff8888ffArathiBasinFu|r: Combat lockdown restriction." ..
										  " Leave combat and try again.")
            end
        end
    }

    
	self.OnMenuRequest = options
	self:RegisterChatCommand({"/arathibasinfu", "/abfu"}, slashMenu)
    waterfall_:Register("ArathiBasinFu", 'aceOptions', options)

end

function ArathiBasinFu:SetupDefaults()
	ArathiBasinFu:RegisterDefaults(
		"profile", 
		{
			messages = {},
			enemyThreshold = 5
		}
	)
end



function ArathiBasinFu:OnInitialize()
	self:RegisterDB("ArathiBasinFuDB", "ArathiBasinFuDBPC")
	self:SetupDefaults()
	self:LoadOptions()
	
	self.clickableTooltip  = true
end

function ArathiBasinFu:OnEnable()
	self:SetDebugging(true)
 	self:Debug("OnEnable called")
end

function ArathiBasinFu:OnDisable()
 	self:Debug("OnDisable called")
end

function ArathiBasinFu:OnClick()
	self:BuildAlertMessage(1)
end

function ArathiBasinFu:AddMessage(v)
	local _, _, name, message = string.find(v, "(.*)%s+#%s+(.*)")
	if not name or not message then return end
	if self.db.profile.messages[name] then
		self:Print(L["Updating %s in custom messages."]:format(name))
		self.db.profile.messages[name] = message
	else
		self:Print(L["Adding %s to custom messages."]:format(name))
		self.db.profile.messages[name] = message
	end
	self:UpdateDisplay()
end

function ArathiBasinFu:RemoveMessage(v)
	if not self.db.profile.messages[v] then return end
	self.db.profile.messages[v] = nil
    self:Print(L["Removed %s from custom messages."]:format(name))
	self:UpdateDisplay()
end

function ArathiBasinFu:OnTooltipUpdate()
	local cat

	cat = tablet_:AddCategory(
			"columns", 1,
			"text", L["Incoming Calls"],
			 "showWithoutChildren", false,
			 "child_justify", "LEFT"
		)
		
	local i = 1
	while i <= self.db.profile.enemyThreshold do
			cat:AddLine(
                "text", L["(%d) Incoming"]:format(i) ,
                "func", "BuildAlertMessage",
				"arg1", self,
				"arg2", i
			)
			
			i = i + 1
	end
	
	cat = tablet_:AddCategory(
			"columns", 1,
			"text", L["Custom Messages"],
			 "showWithoutChildren", false,
			 "child_justify", "LEFT"
	)

	for k, v in pairs(self.db.profile.messages) do
		local name = k
		local message = v
		if name and message then
			cat:AddLine(
				"text", name,
				"func", "PrintAlertMessage",
				"arg1", self,
				"arg2", message,
				"arg3", true
			)
		end
	end
end

